package ar.com.jendrix.common.web.util;

import java.io.IOException;
import java.security.Principal;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import ar.com.jendrix.common.util.Comparator;

public final class FacesContextUtil {

	/**
	 * lee un parametro definido en web.xml <context-param>
	 * 
	 * @param parameter
	 * @return
	 */
	public String getContextParameter(String parameter) {
		FacesContext ctx = FacesContext.getCurrentInstance();
		return ctx.getExternalContext().getInitParameter(parameter);
	}

	/**
	 */
	public static final Object getObject(final String attribute) {
		// Gets the external context.
		final ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();

		// Gets from request.
		Object value = ec.getRequestParameterMap().get(attribute);

		if (Comparator.isEmpty(value)) {
			// Gets from session.
			value = ec.getSessionMap().get(attribute);
		}
		return value;
	}

	/**
	 */
	public static final String getParam(final String attribute) {
		// Gets the external context.
		final ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();

		// Gets from request.
		String value = ec.getRequestParameterMap().get(attribute);

		if (Comparator.isEmpty(value)) {
			// Gets from session.
			value = (String) ec.getSessionMap().get(attribute);
		}
		return value;
	}

	/**
	 */
	public static final String getPrincipalName() {
		// Gets the principal.
		final Principal p = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();

		// Starts empty by default.
		String name = "";

		if (!Comparator.isEmpty(p)) {
			name = p.getName();
		}
		return name;
	}


	/**
	 */
	public static final void sendRedirect(final String pagina) throws IOException {
		final FacesContext context = FacesContext.getCurrentInstance();
		final HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
		response.sendRedirect(pagina);
	}
}